<template>
    <div class="boxs">
        <el-card>
            <el-form :model="queryParams" ref="queryForm" :inline="true">
                <el-form-item label="订单id" prop="name">
                    <el-input v-model="queryParams.orderId" placeholder="Please fill in the order id" clearable
                        size="small" />
                </el-form-item>
                <el-form-item label="商品类型">
                    <el-select v-model="queryParams.productType" @change="handleQuery">
                        <el-option v-for="item in productTypeList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="确认状态">
                    <el-select v-model="queryParams.acknowledgementState" @change="handleQuery">
                        <el-option v-for="item in acknowledgementStateList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="地区">
                    <el-select v-model="queryParams.regionCode" @change="handleQuery">
                        <el-option v-for="item in storefrontList" :key="item.id" :label="item.name"
                            :value="item.name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="起止时间">
                    <el-date-picker v-model="value1" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                        :start-placeholder="$t('table.start')" :end-placeholder="$t('table.end')" @change="timeChange">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="small"
                        @click="handleQuery">{{ $t('table.search') }}</el-button>
                    <el-button icon="el-icon-refresh" size="small"
                        @click="resetQuery">{{ $t('table.reset') }}</el-button>
                </el-form-item>
            </el-form>
            <!-- <div class="flex_between">
                <div></div>
                <el-button type="warning" icon="el-icon-download" size="small"
                    @click="handleExport">{{ $t('table.export') }}</el-button>
            </div> -->
            <el-table border :data="moreArr" style="margin-top: 15px" v-loading="loading">
                <el-table-column label="包名" align="center" prop="packageName" />
                <el-table-column label="商品类型" align="center" prop="productType_str" />
                <el-table-column label="订单id" align="center" prop="orderId" />
                <el-table-column label="token" align="center" prop="purchaseToken" />
                <el-table-column label="订阅时间" align="center" prop="startTime_str" />
                <el-table-column label="确认状态" align="center" prop="acknowledgementState_str" />
                <el-table-column label="商品信息" align="center" prop="lineItems">
                    <template slot-scope="scope">
                        <el-link type="primary" @click="showDevuce(scope.row)">
                            open</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="最新订单id" align="center" prop="latestOrderId" />
                <el-table-column label="地区代码" align="center" prop="regionCode" />
                <el-table-column label="更新时间" align="center" prop="update_date" />
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.size"
                @pagination="getVoidedPurchaseList" />
        </el-card>

        <el-dialog :title="$t('feedback.operate')" :visible.sync="dialogVisible" width="800px">
            <el-form class="demo-form-inline" label-width="140px" :model="form" :rules="rules" ref="ruleForm">
                <el-row v-for="(subscription, index) in form.lineItems" :key="index">
                    <el-col :span="12">
                        <el-form-item label="产品id" prop="reviewId">
                            <el-input disabled v-model="subscription.productId" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="过期时间" prop="reviewId">
                            <el-input disabled v-model="subscription.expiryTime" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="续订信息" prop="reviewId">
                            <el-input disabled v-model="subscription.autoRenewingPlan" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="优惠详情" prop="reviewId">
                            <el-input disabled v-model="subscription.offerDetails" placeholder="" />
                        </el-form-item>
                    </el-col>
                    <el-divider v-if="index < form.lineItems.length - 1"></el-divider>
                </el-row>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import { getVoidedPurchaseList, getVoidedStorefrontList } from "@/api/SubscriptionRevive";
import * as XLSX from "xlsx";

export default {
    name: "notificationList",
    data() {
        return {
            languageContent: '',
            goalLanguage: "zh_CN",
            languageList: [],
            translateLoading: false,
            pkList: [],
            stateList: [
                {
                    id: "0",
                    name: "未处理",
                },
                {
                    id: "1",
                    name: "已处理",
                },
            ],
            queryParams: {
                page: 1,
                size: 10,
                dateRange: {
                    start: "",
                    end: "",
                },
                dateRange2: {
                    start: "",
                    end: "",
                },
                dateRange3: {
                    start: "",
                    end: "",
                },
                state: "",
                pk: "",
                orderId: ''
            },
            total: 0,
            loading: false,
            addLoading: false,
            moreArr: [],
            dialogVisible: false,
            form: {
                comment_type: "",
            },
            search: "",
            rules: {
                comment_type: [
                    { required: true, message: "请输入类型", trigger: "blur" },
                ],
            },
            storefront: [],
            value1: "",
            value2: "",
            value3: "",
            productTypeList: [
                { name: '订阅订单', id: 1 },
                { name: '一次性订单', id: 2 },
            ],
            acknowledgementStateList: [
                { name: '未指定的确认状态', id: 'ACKNOWLEDGEMENT_STATE_UNSPECIFIED' },
                { name: '未确认', id: 'ACKNOWLEDGEMENT_STATE_PENDING' },
                { name: '已确认', id: 'ACKNOWLEDGEMENT_STATE_ACKNOWLEDGED' },
            ],
        };
    },
    created() {
        const { pk } = this.$route.query;
        this.queryParams.pk = pk
        this.getVoidedPurchaseList();
        this.getVoidedStorefrontList();
    },
    methods: {
        async handleExport() {
            this.loading = true;
            let { data } = await getDataListAll(this.queryParams);
            const headers = {
                pk: '包名',
                notification_type: '通知类型',
                subtype: '子类',
                offer_discount_type: '优惠折扣类型',
                price: '续订价格',
                product_id: '产品',
                storefront: '地区代码',
                auto_renew_status: '自动续订',
                expiration_intent: '订阅过期原因',
                original_purchase_date: '首次购买时间',
                renewal_date: '订阅到期时间',
                renewal_price: '下期续订价格',
                update_date: '更新时间',
            };
            const transformedData = data.map(item => {
                const newItem = {};
                for (const key in item) {
                    if (headers[key]) {
                        newItem[headers[key]] = item[key];
                    } else {
                        newItem[key] = item[key];
                    }
                }
                return newItem;
            });
            const ws = XLSX.utils.json_to_sheet(transformedData); // 将JSON转换成sheet
            const wb = XLSX.utils.book_new(); // 新建workbook
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // 在workbook中添加新的sheet
            XLSX.writeFile(wb, "MySpreadsheet.xlsx"); // 写文件并触发下载
            this.loading = false;
        },
        timeChange() {
            this.queryParams.dateRange.start = this.value1[0];
            this.queryParams.dateRange.end = this.value1[1];
            this.handleQuery();
        },
        timeChange2() {
            this.queryParams.dateRange2.start = this.value2[0];
            this.queryParams.dateRange2.end = this.value2[1];
            this.handleQuery();
        },
        timeChange3() {
            this.queryParams.dateRange3.start = this.value3[0];
            this.queryParams.dateRange3.end = this.value3[1];
            this.handleQuery();
        },
        getKeyByValue(object, value) {
            return Object.keys(object).find((key) => object[key] === value);
        },
        async getVoidedStorefrontList() {
            let { data } = await getVoidedStorefrontList(this.queryParams);
            this.storefrontList = data
        },
        formattedDate(iosDate) {
            const date = new Date(iosDate);

            const year = date.getUTCFullYear();
            const month = String(date.getUTCMonth() + 1).padStart(2, '0');
            const day = String(date.getUTCDate()).padStart(2, '0');
            const hours = String(date.getUTCHours()).padStart(2, '0');
            const minutes = String(date.getUTCMinutes()).padStart(2, '0');
            const seconds = String(date.getUTCSeconds()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        async getVoidedPurchaseList() {
            this.loading = true;
            if (this.queryParams.orderId) {
                this.queryParams.orderId = this.queryParams.orderId.trim()
            }
            let { data, total } = await getVoidedPurchaseList(this.queryParams);
            this.loading = false;
            data.forEach(element => {
                switch (element.productType) {
                    case 1:
                        element.productType_str = '订阅订单';
                        break;
                    case 2:
                        element.productType_str = '一次性商品';
                        break;
                }

                // 处理 refundType
                switch (element.refundType) {
                    case 1:
                        element.refundType_str = '完全作废';
                        break;
                    case 2:
                        element.refundType_str = '部分作废';
                        break;
                }

                // 处理 acknowledgementState
                switch (element.acknowledgementState) {
                    case 'ACKNOWLEDGEMENT_STATE_UNSPECIFIED':
                        element.acknowledgementState_str = '未指定';
                        break;
                    case 'ACKNOWLEDGEMENT_STATE_PENDING':
                        element.acknowledgementState_str = '未确认';
                        break;
                    case 'ACKNOWLEDGEMENT_STATE_ACKNOWLEDGED':
                        element.acknowledgementState_str = '已确认';
                        break;
                }

                // 处理 offer_discount_type
                if (element.startTime) {
                    element.startTime_str = this.formattedDate(element.startTime);
                }

            });
            this.moreArr = data;
            this.total = total;
        },



        handleQuery() {
            this.queryParams.page = 1;
            this.getVoidedPurchaseList();
        },
        async affirm() {
            this.form.package_name = this.queryParams.package_name;
            this.$refs["ruleForm"].validate(async (valid) => {
                if (!valid) return;
                try {
                    this.addLoading = true;
                    await editFeedbackState(this.form);
                    this.addLoading = false;
                    this.$message.success("操作成功");
                    this.getVoidedPurchaseList();
                    this.dialogVisible = false;
                } catch (e) {
                    this.addLoading = false;
                }
            });
        },
        openDialog() {
            this.form = {};
            this.dialogVisible = true;
        },
        showDevuce(row) {
            if (typeof row.lineItems === 'string') {
                row.lineItems = JSON.parse(row.lineItems);
            }
            row.lineItems.forEach(x => {

                x.expiryTime = this.formattedDate(x.expiryTime)
                if (typeof x.autoRenewingPlan != 'string') {
                    x.autoRenewingPlan = JSON.stringify(x.autoRenewingPlan);
                }
                if (typeof x.offerDetails != 'string') {
                    x.offerDetails = JSON.stringify(x.offerDetails);
                }
            })
            this.form = { ...row };
            this.dialogVisible = true;
        },
        handleDelete(index, row) {
            this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "error",
            }).then(async () => {
                await deleteTemplateType({ id: row.id });
                this.getVoidedPurchaseList();
                this.$message({
                    message: "删除成功！",
                    type: "success",
                });
            });
        },
        resetQuery() {
            this.queryParams.orderId = null;
            this.queryParams.productType = null;
            this.queryParams.acknowledgementState = null;
            this.queryParams.regionCode = null;
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.queryParams.dateRange2.start = null;
            this.queryParams.dateRange2.end = null;
            this.queryParams.dateRange3.start = null;
            this.queryParams.dateRange3.end = null;
            this.queryParams.page = 1;
            this.value1 = "";
            this.value2 = "";
            this.value3 = "";
            this.getVoidedPurchaseList();
        },
    },
};
</script>
<style lang="scss" scoped>
.boxs {
    padding: 20px;
}

::v-deep.el-input.is-disabled .el-input__inner {
    color: #333 !important;
}

::v-deep.el-textarea.is-disabled .el-textarea__inner {
    color: #333 !important;
}

::v-deep .el-image {
    margin-right: 8px;
    border-radius: 4px;
}
</style>